const app = getApp();
const { request } = require('../../../utils/request');
const api = require('../../../utils/api.js');
const codeApi = require('../../../utils/codeApi.js');

Page({
  /**
   * 页面的初始数据
   */
  data: {
    loading: true,
    agentInfo: null,
    teamMembers: [],
    totalMembers: 0,
    directTeamCount: 0,
    searchValue: '',
    
    // 分页相关
    pageSize: 10,
    currentPage: 1,
    hasMore: false,
    
    // 排序相关
    sortOptions: [
      { value: 'join_time', label: '加入时间', order: 'desc' },
      { value: 'sales', label: '销售额', order: 'desc' },
      { value: 'name', label: '姓名', order: 'asc' }
    ],
    currentSort: { field: 'join_time', order: 'desc' },
    
    // 操作相关
    showActionSheet: false,
    currentMember: null,
    actionSheetItems: [
      { text: '查看详情', value: 'detail' },
      { text: '发送消息', value: 'message' },
      { text: '调整分成', value: 'commission' }
    ]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 检查代理权限
    this.checkAgentPermission();
  },

  /**
   * 检查代理权限
   */
  checkAgentPermission() {
    const userId = wx.getStorageSync('userId');
    
    if (!userId) {
      wx.showModal({
        title: '提示',
        content: '未登录或登录已过期，请先登录',
        showCancel: false,
        success: () => {
          wx.navigateTo({
            url: '/pages/login/login'
          });
        }
      });
      return;
    }
    
    codeApi.checkPermission(userId)
    .then(res => {
      if (res.code === 0 && res.data && res.data.has_permission) {
        this.setData({
          agentInfo: res.data.agent_info || {}
        });
        
        // 获取团队成员
        this.fetchTeamMembers();
      } else {
        wx.showModal({
          title: '提示',
          content: '您暂无代理管理权限',
          showCancel: false,
          success: () => {
            wx.navigateBack();
          }
        });
      }
    })
    .catch(err => {
      console.error('检查权限失败', err);
      
      wx.showToast({
        title: '网络错误',
        icon: 'none',
        success: () => {
          setTimeout(() => {
            wx.navigateBack();
          }, 1500);
        }
      });
    });
  },

  /**
   * 获取团队成员
   */
  fetchTeamMembers(refresh = true) {
    if (refresh) {
      this.setData({
        currentPage: 1,
        teamMembers: []
      });
    }
    
    const { agentInfo, pageSize, currentPage, searchValue, currentSort } = this.data;
    
    if (!agentInfo || !agentInfo.id) {
      this.setData({ loading: false });
      return;
    }
    
    const params = {
      agent_id: agentInfo.id,
      page: currentPage,
      page_size: pageSize,
      sort_field: currentSort.field,
      sort_order: currentSort.order
    };
    
    if (searchValue) {
      params.keyword = searchValue;
    }
    
    this.setData({ loading: true });
    
    request(api.agent_team_members, 'GET', params)
    .then(res => {
      if (res.code === 0 && res.data) {
        const newMembers = res.data.list || [];
        const totalMembers = res.data.total || 0;
        
        this.setData({
          teamMembers: refresh ? newMembers : [...this.data.teamMembers, ...newMembers],
          totalMembers,
          directTeamCount: newMembers.length,
          hasMore: newMembers.length === pageSize && (currentPage * pageSize) < totalMembers,
          loading: false
        });
        
        // 获取团队总人数
        this.fetchTeamTotalCount();
      } else {
        this.setData({ loading: false });
        wx.showToast({
          title: res.message || '获取团队成员失败',
          icon: 'none'
        });
      }
    })
    .catch(err => {
      console.error('获取团队成员失败', err);
      this.setData({ loading: false });
      wx.showToast({
        title: '网络错误',
        icon: 'none'
      });
    });
  },

  /**
   * 获取团队总人数（包括间接下级）
   */
  fetchTeamTotalCount() {
    const { agentInfo } = this.data;
    
    if (!agentInfo || !agentInfo.id) return;
    
    const params = {
      agent_id: agentInfo.id
    };
    
    // 使用团队层级结构API获取总人数
    request(api.agent_team_hierarchy, 'GET', params)
    .then(res => {
      if (res.code === 0 && res.data && res.data.stats) {
        this.setData({
          totalMembers: res.data.stats.total_members || 0
        });
      }
    })
    .catch(err => {
      console.error('获取团队总人数失败', err);
    });
  },

  /**
   * 搜索团队成员
   */
  onSearch(e) {
    const searchValue = e.detail;
    this.setData({ searchValue }, () => {
      this.fetchTeamMembers();
    });
  },

  /**
   * 清除搜索内容
   */
  onClearSearch() {
    this.setData({ searchValue: '' }, () => {
      this.fetchTeamMembers();
    });
  },

  /**
   * 改变排序方式
   */
  changeSortOrder(e) {
    const { field } = e.currentTarget.dataset;
    const { currentSort, sortOptions } = this.data;
    
    // 如果点击当前排序字段，则切换排序方向
    if (field === currentSort.field) {
      const newOrder = currentSort.order === 'asc' ? 'desc' : 'asc';
      this.setData({
        currentSort: { field, order: newOrder }
      }, () => {
        this.fetchTeamMembers();
      });
    } else {
      // 寻找默认排序方向
      const sortOption = sortOptions.find(item => item.value === field);
      if (sortOption) {
        this.setData({
          currentSort: { field, order: sortOption.order }
        }, () => {
          this.fetchTeamMembers();
        });
      }
    }
  },

  /**
   * 加载更多
   */
  loadMore() {
    if (this.data.hasMore && !this.data.loading) {
      this.setData({
        currentPage: this.data.currentPage + 1
      }, () => {
        this.fetchTeamMembers(false);
      });
    }
  },

  /**
   * 点击成员，显示操作菜单
   */
  tapMember(e) {
    const { member } = e.currentTarget.dataset;
    
    this.setData({
      currentMember: member,
      showActionSheet: true
    });
  },

  /**
   * 关闭操作菜单
   */
  closeActionSheet() {
    this.setData({
      showActionSheet: false
    });
  },

  /**
   * 执行操作
   */
  handleAction(e) {
    const value = e.currentTarget.dataset.value;
    const { currentMember } = this.data;
    
    this.setData({ showActionSheet: false });
    
    if (!currentMember) return;
    
    switch (value) {
      case 'detail':
        this.navigateToMemberDetail(currentMember);
        break;
      case 'message':
        this.sendMessageToMember(currentMember);
        break;
      case 'commission':
        this.adjustCommission(currentMember);
        break;
    }
  },

  /**
   * 查看成员详情
   */
  navigateToMemberDetail(member) {
    wx.navigateTo({
      url: `/pages/admin/team-member-detail/team-member-detail?id=${member.id}`
    });
  },

  /**
   * 发送消息
   */
  sendMessageToMember(member) {
    wx.navigateTo({
      url: `/pages/message/chat/chat?userId=${member.user_id}&name=${encodeURIComponent(member.name)}`
    });
  },

  /**
   * 调整分成比例
   */
  adjustCommission(member) {
    wx.navigateTo({
      url: `/pages/admin/adjust-commission/adjust-commission?id=${member.id}&name=${encodeURIComponent(member.name)}&current=${member.commission_rate}`
    });
  },

  /**
   * 添加成员
   */
  addTeamMember() {
    wx.navigateTo({
      url: '/pages/admin/invite-member/invite-member'
    });
  },

  /**
   * 查看团队层级结构
   */
  viewTeamHierarchy() {
    wx.navigateTo({
      url: '/pages/admin/team-hierarchy/team-hierarchy'
    });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // 如果已经有代理信息，刷新团队成员列表
    if (this.data.agentInfo) {
      this.fetchTeamMembers();
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.fetchTeamMembers();
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    this.loadMore();
  }
}) 